import { getQuestionTypeByActionCodeApi } from "@/api";
import { Button } from "@mui/material";
import React, { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import SelectOption from "./components/SelectOption";
import "./index.less";

interface IParams {
  code: string;
  // 索引器，在ts里面类型需要有索引器才能使用  obj[] 的方式修改或者获取数据
  [index: string]: string;
}

// 定义一个 试题分类的数组
const testTypes = [
  { key: "全部", value: "all" },
  { key: "未做", value: "notdone" },
  { key: "已做", value: "done" },
  { key: "错误", value: "err" },
];

const testNums = [
  { key: "5", value: "5" },
  { key: "10", value: "10" },
  { key: "20", value: "20" },
  { key: "30", value: "30" },
  { key: "50", value: "50" },
  { key: "100", value: "100" },
];

const qsType2Chines: KeyMap = {
  all: "全部",
  qa: "问答",
  fill: "填空",
  one: "单选",
  check: "判断",
  code: "编程",
  many: "多选",
};

export default function Select() {
  // 获取从 home 传递过来的actionCode
  const data = useParams<IParams>();
  const nav = useNavigate();
  // 定义好3个要传递到 练习页面的 参数
  const [testNum, setTestNum] = useState(5);
  const [testType, setTestType] = useState("all");
  const [questionType, setQuestionType] = useState("all");
  // actionCode是从路由里面获取的
  const actionCode = data.code;

  const [questionTypes, setQuestionTypes] = useState<
    { key: string; value: string }[]
  >([]);
  // 一开始根据 actionCode 向服务器发请求获取 题目的分类数据
  useEffect(() => {
    getQuestionTypeByActionCodeApi(data.code!).then((res) => {
      if (res.errCode === 0) {
        // 服务器返回的数据是不满足我们的使用要求的，需要 需要我们自己进行加工
        // 目标样式： {key:中文(数量),value:英文}[]
        // 现有的数据： {key:英文,value:数量}[]
        const arr = res.data.map((item) => {
          return {
            key: qsType2Chines[item.key] + "(" + item.value + ")",
            value: item.key,
          };
        });
        setQuestionTypes(arr);
      }
    });
  }, []);

  return (
    <div className="select">
      <div className="flex">
        <Button
          variant="contained"
          onClick={() =>
            nav("/practice", {
              state: {
                testNum,
                testType,
                actionCode,
                questionType,
              },
            })
          }
        >
          进入练习模式
        </Button>
        <Button variant="contained" color="warning">
          进入考试模式
        </Button>
      </div>
      <SelectOption
        title="试题分类"
        list={testTypes}
        onChange={(value) => setTestType(value)}
      />
      <SelectOption
        title="题目类型"
        list={questionTypes}
        onChange={(value) => setQuestionType(value)}
      />
      <SelectOption
        title="做题数量"
        list={testNums}
        onChange={(value) => setTestNum(parseInt(value))}
      />
    </div>
  );
}
